package com.hfi.security.app.validatecode;

import com.hfi.security.core.validate.code.ValidateCode;
import com.hfi.security.core.validate.code.ValidateCodeException;
import com.hfi.security.core.validate.code.ValidateCodeRepository;
import com.hfi.security.core.validate.code.ValidateCodeType;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;

import java.util.concurrent.TimeUnit;

/**
 * @author ChangLiang
 * @date 2019/9/1
 */
@Component
public class RedisValidateCodeRepository implements ValidateCodeRepository {

    /**
     * 默认是<Object,Object>
     */
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void save(ServletWebRequest servletWebRequest, ValidateCode validateCode,
                     ValidateCodeType validateCodeType) {
        redisTemplate.opsForValue().set(buildKey(servletWebRequest, validateCodeType), validateCode, 5,
                TimeUnit.MINUTES);
    }

    @Override
    public ValidateCode get(ServletWebRequest servletWebRequest, ValidateCodeType validateCodeType) {
        Object value = redisTemplate.opsForValue().get(buildKey(servletWebRequest, validateCodeType));
        // 避免NPE
        if (value == null) {
            return null;
        }
        return (ValidateCode) value;
    }

    @Override
    public void remove(ServletWebRequest servletWebRequest, ValidateCodeType validateCodeType) {
        redisTemplate.delete(buildKey(servletWebRequest,validateCodeType));
    }

    /**
     * 根据http header中的deviceId构建redis key
     *
     * @param request
     * @param validateCodeType
     * @return
     */
    private String buildKey(ServletWebRequest request, ValidateCodeType validateCodeType) {
        String deviceId = request.getHeader("deviceId");
        if (StringUtils.isBlank(deviceId)) {
            throw new ValidateCodeException("请在请求头中携带deviceId参数");
        }
        return "code:" + validateCodeType.toString().toLowerCase() + ":" + deviceId;
    }
}
